<template>
	<view class="container">
		<!-- 搜索和筛选区域 -->
		<view class="filter-section">
			<view class="search-box">
				<uni-search-bar v-model="searchKeyword" placeholder="搜索商品名称" @confirm="handleSearch" @clear="handleSearch" />
			</view>
			
			<view class="filter-options">
				<view class="filter-item">
					<uni-data-select v-model="filterStatus" :localdata="statusOptions" placeholder="商品状态" @change="handleSearch" />
				</view>
				<view class="filter-item">
					<uni-data-select v-model="filterShelf" :localdata="shelfOptions" placeholder="上下架状态" @change="handleSearch" />
				</view>
				<view class="filter-item">
					<button class="add-btn" @click="navigateToAdd">添加商品</button>
				</view>
			</view>
		</view>
		
		<!-- 商品列表 -->
		<view class="product-list">
			<view class="product-item" v-for="(item, index) in productList" :key="index">
				<view class="product-header">
					<image class="product-image" :src="item.images && item.images.length > 0 ? item.images[0] : defaultImage" mode="aspectFill" @click="previewImage(item.images, 0)"></image>
					<view class="product-info">
						<text class="product-name">{{item.name}}</text>
						<view class="product-category">
							<text>分类: {{formatCategory(item.categoryPath)}}</text>
						</view>
						<view class="product-price">
							<text class="price">¥{{item.price}}</text>
							<text class="price-range" v-if="item.minPrice && item.maxPrice">¥{{item.minPrice}} - ¥{{item.maxPrice}}</text>
							<text class="fixed-price" v-if="item.fixedPrice">一口价: ¥{{item.fixedPrice}}</text>
						</view>
					</view>
				</view>
				
				<view class="product-content">
					<view class="product-detail">
						<view class="detail-item">
							<text class="label">所属人:</text>
							<text class="value">{{item.owner || '未设置'}}</text>
						</view>
						<view class="detail-item">
							<text class="label">空闲时间:</text>
							<text class="value">{{item.availableTime || '未设置'}}</text>
						</view>
						<view class="detail-item">
							<text class="label">创建时间:</text>
							<text class="value">{{formatDate(item.createTime)}}</text>
						</view>
					</view>
					
					<view class="product-status">
						<view :class="['status-tag', getStatusClass(item.status)]">{{getStatusText(item.status)}}</view>
						<view :class="['shelf-tag', item.isOnShelf ? 'on-shelf' : 'off-shelf']">{{item.isOnShelf ? '已上架' : '已下架'}}</view>
					</view>
				</view>
				
				<view class="product-actions">
					<button class="action-btn edit" @click="editProduct(item)">编辑</button>
					<button class="action-btn" :class="item.isOnShelf ? 'off-shelf-btn' : 'on-shelf-btn'" @click="toggleShelf(item)">
						{{item.isOnShelf ? '下架' : '上架'}}
					</button>
					<button class="action-btn delete" @click="confirmDelete(item)">删除</button>
				</view>
			</view>
			
			<uni-load-more :status="loadMoreStatus" />
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="productList.length === 0 && !loading">
			<image src="/static/images/empty-product.png" mode="aspectFit"></image>
			<text>暂无商品</text>
		</view>
	</view>
</template>

<script>
	import { getProducts, updateProductStatus, deleteProduct } from '@/api/pet/product.js';
	
	export default {
		data() {
			return {
				productList: [],
				page: 1,
				limit: 10,
				total: 0,
				loading: false,
				loadMoreStatus: 'more',
				defaultImage: '/static/images/default-product.png',
				searchKeyword: '',
				filterStatus: '',
				filterShelf: '',
				statusOptions: [
					{ value: '', text: '全部状态' },
					{ value: '1', text: '出售中' },
					{ value: '2', text: '已售出' },
					{ value: '3', text: '已取消' },
					{ value: '4', text: '锁定中' }
				],
				shelfOptions: [
					{ value: '', text: '全部' },
					{ value: '1', text: '已上架' },
					{ value: '0', text: '已下架' }
				]
			}
		},
		onLoad() {
			this.loadProducts();
		},
		onPullDownRefresh() {
			this.page = 1;
			this.productList = [];
			this.loadProducts().then(() => {
				uni.stopPullDownRefresh();
			});
		},
		onReachBottom() {
			if (this.productList.length < this.total) {
				this.page++;
				this.loadProducts();
			}
		},
		methods: {
			async loadProducts() {
				if (this.loading) return;
				
				this.loading = true;
				this.loadMoreStatus = 'loading';
				
				try {
					const res = await getProducts({
						page: this.page,
						limit: this.limit,
						keyword: this.searchKeyword,
						status: this.filterStatus,
						isOnShelf: this.filterShelf
					});
					
					if (res.code === 200) {
						if (this.page === 1) {
							this.productList = res.data.list;
						} else {
							this.productList = [...this.productList, ...res.data.list];
						}
						
						this.total = res.data.total;
						
						if (this.productList.length >= this.total) {
							this.loadMoreStatus = 'noMore';
						} else {
							this.loadMoreStatus = 'more';
						}
					}
				} catch (error) {
					console.error('Failed to load products:', error);
					this.loadMoreStatus = 'fail';
				} finally {
					this.loading = false;
				}
			},
			formatDate(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			},
			formatCategory(categoryPath) {
				if (!categoryPath) return '未分类';
				return categoryPath.split(',').join(' > ');
			},
			getStatusText(status) {
				const statusMap = {
					1: '出售中',
					2: '已售出',
					3: '已取消',
					4: '锁定中'
				};
				return statusMap[status] || '未知状态';
			},
			getStatusClass(status) {
				const classMap = {
					1: 'selling',
					2: 'sold',
					3: 'canceled',
					4: 'locked'
				};
				return classMap[status] || '';
			},
			handleSearch() {
				this.page = 1;
				this.productList = [];
				this.loadProducts();
			},
			navigateToAdd() {
				uni.navigateTo({
					url: '/pages/pet/product-edit'
				});
			},
			editProduct(item) {
				uni.navigateTo({
					url: `/pages/pet/product-edit?id=${item.id}`
				});
			},
			async toggleShelf(item) {
				try {
					const newStatus = !item.isOnShelf;
					const res = await updateProductStatus(item.id, {
						isOnShelf: newStatus
					});
					
					if (res.code === 200) {
						uni.showToast({
							title: newStatus ? '商品已上架' : '商品已下架',
							icon: 'success'
						});
						
						// 更新本地数据
						const index = this.productList.findIndex(p => p.id === item.id);
						if (index !== -1) {
							this.productList[index].isOnShelf = newStatus;
						}
					}
				} catch (error) {
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},
			confirmDelete(item) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除商品"${item.name}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							this.deleteProduct(item.id);
						}
					}
				});
			},
			async deleteProduct(id) {
				try {
					const res = await deleteProduct(id);
					
					if (res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						
						// 从列表中移除
						this.productList = this.productList.filter(item => item.id !== id);
					}
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				}
			},
			previewImage(images, current) {
				if (!images || images.length === 0) return;
				
				uni.previewImage({
					urls: images,
					current: images[current]
				});
			}
		}
	}
</script>

<style lang="scss">
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.filter-section {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.filter-options {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		
		.filter-item {
			width: 33.33%;
			padding: 0 10rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;
			
			.add-btn {
				background-color: #007AFF;
				color: #FFFFFF;
				font-size: 28rpx;
				height: 70rpx;
				line-height: 70rpx;
				border-radius: 35rpx;
			}
		}
	}
}

.product-list {
	.product-item {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		
		.product-header {
			display: flex;
			margin-bottom: 20rpx;
			
			.product-image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}
			
			.product-info {
				flex: 1;
				
				.product-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 10rpx;
				}
				
				.product-category {
					font-size: 26rpx;
					color: #666;
					margin-bottom: 10rpx;
				}
				
				.product-price {
					display: flex;
					flex-wrap: wrap;
					align-items: center;
					
					.price {
						font-size: 32rpx;
						color: #FF5722;
						font-weight: bold;
						margin-right: 16rpx;
					}
					
					.price-range {
						font-size: 26rpx;
						color: #999;
						margin-right: 16rpx;
					}
					
					.fixed-price {
						font-size: 26rpx;
						color: #FF9800;
					}
				}
			}
		}
		
		.product-content {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
			
			.product-detail {
				flex: 1;
				
				.detail-item {
					display: flex;
					font-size: 26rpx;
					margin-bottom: 8rpx;
					
					.label {
						color: #999;
						width: 150rpx;
					}
					
					.value {
						color: #333;
						flex: 1;
					}
				}
			}
			
			.product-status {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				
				.status-tag, .shelf-tag {
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					margin-bottom: 10rpx;
				}
				
				.status-tag {
					&.selling {
						background-color: #E8F5E9;
						color: #4CAF50;
					}
					
					&.sold {
						background-color: #E3F2FD;
						color: #2196F3;
					}
					
					&.canceled {
						background-color: #FFEBEE;
						color: #F44336;
					}
					
					&.locked {
						background-color: #FFF8E1;
						color: #FFC107;
					}
				}
				
				.shelf-tag {
					&.on-shelf {
						background-color: #E8F5E9;
						color: #4CAF50;
					}
					
					&.off-shelf {
						background-color: #EEEEEE;
						color: #9E9E9E;
					}
				}
			}
		}
		
		.product-actions {
			display: flex;
			justify-content: flex-end;
			padding-top: 16rpx;
			border-top: 1rpx solid #f0f0f0;
			
			.action-btn {
				margin-left: 20rpx;
				font-size: 26rpx;
				padding: 0 30rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 30rpx;
				
				&.edit {
					background-color: #FFFFFF;
					color: #007AFF;
					border: 1rpx solid #007AFF;
				}
				
				&.on-shelf-btn {
					background-color: #4CAF50;
					color: #FFFFFF;
				}
				
				&.off-shelf-btn {
					background-color: #9E9E9E;
					color: #FFFFFF;
				}
				
				&.delete {
					background-color: #FFFFFF;
					color: #F44336;
					border: 1rpx solid #F44336;
				}
			}
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding-top: 200rpx;
	
	image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	text {
		font-size: 28rpx;
		color: #999;
	}
}
</style>